import time
from urllib import request
import json

from api.api_project import Public_Data


# region 从once中获取文件的json
def __get_ulr(project, channel_code, period=""):
    """
        根据通信渠道号、项目和查询的周期生成查询的网址
    """
    url_base = r"http://once/once/document_search?"
    para_time = f"t={str(int(time.time() * 1000))}"
    para1 = f"currentAppCode=app_ae_document&searchParams=%257B%2522searchTerm%2522%3A%2522*{project}*{channel_code}*%2522%2C%2522c_project_code%2522%3A%2522{project}%2522%257D"
    end_str = f"&clearFacet=true&indexRange=&searchVersion=&searchMode=AND&validDateRange={period}&sortType=r_creation_date%7Cdesc&pageSize=1000&pageIndex="
    url = url_base + para_time + para1 + end_str
    return url


def __get_once_json(url, index_page):
    public_data = Public_Data()
    """根据地址和页码获取查询的数据"""
    if public_data.Token:
        headers = ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko')
        url_str = url + str(index_page) + "&" + public_data.Token

        opener = request.build_opener()
        opener.addheaders = [headers]

        body = "html"
        times = 0
        while "html" in body and times < 5:
            req = opener.open(url_str)
            body = req.read().decode('utf-8')
            times += 1

        return json.loads(body)
    print("获取登录验证不成功！")


def get_once_json(project, channel_code, period="", index_page=1):
    url = __get_ulr(project, channel_code, period)
    return __get_once_json(url, index_page)


# endregion


# region 处理json 数据
# 处理函件Json

def get_channel(info_str: str, label_str: str):
    data0 = info_str.split(label_str)[-1]
    data1 = data0.split("】")
    data2 = data1[1].split("<")
    return data2[0]


def dic_to_fax(file_json: dict, contract: list) -> dict:
    """
    contract:["id", "project", "channel_code", "lot_code", "factory",""author_code""]
    将页面函件信息字典转为函件表的字典信息
    """
    fax = dict()
    # region 设置初始值:
    """
    { 'once_id':"", 
      'fax_type', 
      'channel', 
      'code',
      'title', 
      'date_effect', 
      'reply_fax', 
      'replied_fax',
       'note', 
      'invalid', 
      'contract_id', 
      'look_up_str'}
    """
    fax["once_id"] = 0
    fax["fax_type"] = ""
    fax["channel"] = ""
    fax["code"] = ""
    fax["title"] = ""
    fax["date_effect"] = ""
    fax["reply_fax"] = ""
    fax["replied_fax"] = ""
    fax["note"] = ''
    fax["invalid"] = 0
    fax["contract_id"] = 0
    fax["look_up_str"] = ''
    # end region
    fax["contract_id"] = contract[0]
    fax["once_id"] = file_json["id"]
    fax["title"] = file_json["description"]
    fax["channel"] = file_json["title"].strip()
    fax["invalid"] = 1 if file_json["INV"] else 0
    for info_dic in file_json["otherFields"]:
        if info_dic["code"] == "c_letter_type":
            fax["fax_type"] = info_dic["value"]
        if info_dic["code"] == "c_valid_date":
            fax["date_effect"] = info_dic["value"]
        if info_dic["code"] == "c_reply_channel":
            fax["reply_fax"] = info_dic["value"]
        if info_dic["code"] == "reply_to_channel":
            fax["replied_fax"] = info_dic["value"]
    result = file_json["highLightingFields"]
    if result:
        if "被答复渠道号" in result:
            fax["replied_fax"] = get_channel(result, "被答复渠道号")
        if "回文号" in result:
            fax["reply_fax"] = get_channel(result, "回文号")
    # contract:{contract[0]},project:{contract[1]},lot_code:{contract[3]},factory: {contract[4]},
    fax["look_up_str"] = f'file:{fax["channel"]}, {fax["title"]} {fax["date_effect"]} '
    return fax


# 处理文件json
def dic_to_doc(file_json: dict, contract: list):
    """返回
    {"doc_type": doc_type, "doc": document}
    doc_type: "doc_f" ,"doc_e"
    """
    document = {'once_id': "", 'code': "", 'rev': "", 'inner_code': "", 'title': "", 'date_public': "", 'newest': 1,
                'doc_type': "", 'channel': "", 'reviewed': 0, 'reviewed_result': "", 'drcs_channel': "",
                'file_name': "",
                'author_code': "", 'note': "", 'invalid': 0, "is_wr": 1, 'contract_id': 0,
                'look_up_str': ""}
    document["contract_id"] = contract[0]
    document["once_id"] = file_json["id"]
    document["newest"] = 1 if file_json["NEW"] else 0

    document["is_wr"] = 1 if file_json["WR"] else 0
    document["title"] = file_json["firstFields"][0]["hlValue"]
    document["file_name"] = file_json["title"]

    for info_data in file_json["otherFields"]:
        if info_data["code"] == "c_record_code":
            document["code"] = info_data["value"].strip()
            continue
        if info_data["code"] == "c_revision":
            document["rev"] = info_data["value"]
            continue
        if info_data["code"] == "c_internal_identity":
            document["inner_code"] = info_data["value"]
            continue
        if info_data["code"] == "c_transmital_channel":
            channel_code_str = info_data["value"]

            channels = channel_code_str.split()
            for channel in channels:
                if contract[2] in channel:
                    document["channel"] = channel.strip()
                    break
            continue
        if info_data["code"] == "c_valid_date":
            document['date_public'] = info_data["value"]
            continue
        if info_data["code"] == "c_review_channel":
            document['drcs'] = info_data["value"]

        document['author_code'] = document["code"][11:15]
    # 文件审查
    result = file_json["highLightingFields"]
    doc_type = "doc_e"
    document["reviewed"] = 0
    if contract[-1] in document["code"] and result:
        doc_type = "doc_f"

        if "review_result" in result:
            reviewed_result = ""
            if "ACC" in result:
                reviewed_result = "ACC"
            if "AEN" in result:
                reviewed_result = "AEN"
            if "RFC" in result:
                reviewed_result = "RFC"
            if reviewed_result:
                document["reviewed_result"] = reviewed_result
                document["reviewed"] = 1
    #  查询字段包含 项目+采购包+制造厂+finish=1+文件名+标题+内部编码+通道号+生效日期+合同id
    doc_status_info = f'reviewed={document["reviewed"]},newest={document["newest"]} ,'
    doc_info = f'file:{document["channel"]} ,{document["file_name"]} ,{document["title"]} ,{document["inner_code"]}, {document["date_public"]}'
    document["look_up_str"] = doc_status_info + doc_info

    return {"doc_type": doc_type, "doc": document}

# endregion
